﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JX.Infrastructure.Common;
using JX.Infrastructure;
using JX.Infrastructure.TencentCaptcha;
using MimeKit;
using System.Text;
using JX.Application;
using JX.Core.Entity;
using JX.Infrastructure.Log;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.Contracts;
using System.Data;
using JXWebSite.Components;

namespace JXWebSite.Controllers
{
	/// <summary>
	/// 公共模块控制器
	/// </summary>
    public class CommonController : Controller
    {
		private IRegionServiceAppDapper _RegionServiceApp;
		private INodesServiceAppDapper _NodesServiceApp;
		private ICommonInfoServiceAppDapper _CommonInfoServiceApp;
		private IUsersServiceAppDapper _UsersServiceApp;
		private IAdminServiceAppDapper _AdminServiceApp;
		/// <summary>
		/// 依赖注入
		/// </summary>
		/// <param name="regionServiceApp"></param>
		/// <param name="nodesServiceApp"></param>
		/// <param name="commonInfoServiceApp"></param>
		/// <param name="usersServiceApp"></param>
		/// <param name="AdminServiceApp"></param>
		public CommonController(IRegionServiceAppDapper regionServiceApp,
			INodesServiceAppDapper nodesServiceApp,
			ICommonInfoServiceAppDapper commonInfoServiceApp,
			IUsersServiceAppDapper usersServiceApp,
			IAdminServiceAppDapper AdminServiceApp)
		{
			_RegionServiceApp = regionServiceApp;
			_NodesServiceApp = nodesServiceApp;
			_CommonInfoServiceApp = commonInfoServiceApp;
			_UsersServiceApp = usersServiceApp;
			_AdminServiceApp = AdminServiceApp;
		}

		/// <summary>
		/// 上传文件
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public async Task<IActionResult> UploadHandle()
		{
			ResultInfo resultInfo = new ResultInfo();
			var uploadConfig = ConfigHelper.Get<UploadFilesConfig>();
			if (!uploadConfig.EnableUploadFiles)
			{
				resultInfo.Msg = "没有开启上传权限";
				return Json(resultInfo);
			}
			var formFile = Request.Form.Files[0];
			resultInfo = await Utility.FileUploadSaveAs(formFile);
			return Json(resultInfo);
		}

		/// <summary>
		/// 上传图片
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public async Task<IActionResult> UploadImageHandle()
		{
			ResultInfo resultInfo = new ResultInfo();
			var uploadConfig = ConfigHelper.Get<UploadFilesConfig>();
			if (!uploadConfig.EnableUploadFiles)
			{
				resultInfo.Msg = "没有开启上传权限";
				return Json(resultInfo);
			}
			bool isThumb = DataConverter.CBoolean(Utility.Request("isThumb", "false")); 
			bool isWaterMark = DataConverter.CBoolean(Utility.Request("isWaterMark", "false"));
			string allowedExtensions = Utility.Request("allowedExtensions");
			var formFile = Request.Form.Files[0];
			resultInfo = await Utility.FileUploadSaveAs(formFile, "", allowedExtensions, "", isThumb, isWaterMark);
			return Json(resultInfo);
		}

		/// <summary>
		/// 上传excel文件
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public async Task<IActionResult> UploadExcelHandle()
		{
			ResultInfo resultInfo = new ResultInfo();
			var uploadConfig = ConfigHelper.Get<UploadFilesConfig>();
			if (!uploadConfig.EnableUploadFiles)
			{
				resultInfo.Msg = "没有开启上传权限";
				return Json(resultInfo);
			}
			resultInfo = await ExcelHelper.UploadExcel();
			if (resultInfo.Status == 1)
			{
				var dt = ExcelHelper.ExcelToTable(resultInfo.Data);
				//把数据存入数据库

			}
			return Json(resultInfo);
		}

		/// <summary>
		/// 导出excel
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult ExportExcel()
		{
			//得到数据源
			var dt = new DataTable();

			var buffer = ExcelHelper.TableToExcel(dt);
			return File(buffer, "application/ms-excel", "myExcel.xlsx");
		}

		/// <summary>
		/// 图形验证码
		/// </summary>
		/// <returns></returns>
		public IActionResult ValidateCode()
		{
			string code = "";
			System.IO.MemoryStream ms = ValidateCodeHelper.CreateValidateCode(out code);
			Utility.SetSession("LoginValidateCode", code);
			Response.Body.Dispose();
			return File(ms.ToArray(), @"image/png");
		}

		/// <summary>
		/// 模型中使用的图形验证码
		/// </summary>
		/// <returns></returns>
		public IActionResult ValidateCodeByModel()
		{
			string code = "";
			System.IO.MemoryStream ms = ValidateCodeHelper.CreateValidateCode(out code);
			Utility.SetSession("ModelValidateCode", code);
			Response.Body.Dispose();
			return File(ms.ToArray(), @"image/png");
		}

		/// <summary>
		/// 检查模型中使用的图形验证码
		/// </summary>
		/// <returns></returns>
		[HttpPost, HttpGet]
		public IActionResult CheckValidateCodeByModel()
		{
			ResultInfo resultInfo = new ResultInfo();
			string param1 = Utility.Request("param1", "");
			string code = DataConverter.ToString(Utility.GetSession("ModelValidateCode"));
			if (string.Compare(param1, code, true) != 0)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "验证码不对";
				return Json(resultInfo);
			}
			else
			{
				resultInfo.Status = 1;
				resultInfo.Msg = "验证码正确";
				return Json(resultInfo);
			}
		}

		/// <summary>
		/// 发送短信
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult SendCodeSMS()
		{
			string mobile = Utility.Request("mobile", "");//手机号
			string ticket = Utility.Request("ticket", "");//腾讯验证码客户端验证回调的票据
			string randstr = Utility.Request("randstr", "");//腾讯验证码客户端验证回调的随机串
			ResultInfo resultInfo = new ResultInfo();
			if (string.IsNullOrEmpty(mobile))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "手机号不能为空";
				return Json(resultInfo);
			}
			if (string.IsNullOrEmpty(ticket))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "ticket不能为空";
				return Json(resultInfo);
			}
			if (string.IsNullOrEmpty(randstr))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "randstr不能为空";
				return Json(resultInfo);
			}
			if (TencentCaptchaUtility.CheckTicket(ticket, randstr, Utility.GetClientIP()))
			{
				//调用发送短信接口

				resultInfo.Status = 1;
				resultInfo.Msg = "发送成功";
				return Json(resultInfo);
			}
			else
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "ticket验证不通过，发送失败！";
				return Json(resultInfo);
			}
		}

		/// <summary>
		/// 发送邮件
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult SendMail()
		{
			string mailToAddress = Utility.Request("mailToAddress", "");//收件人地址
			string subject = Utility.Request("subject", "这是一封测试邮件");//邮件标题
			string mailBody = Utility.Request("mailBody", "这是一封测试邮件，如果您可以成功收到此邮件，则说明您的“邮件参数配置”设置正确。",false);//邮件内容
			ResultInfo resultInfo = new ResultInfo();
			if (string.IsNullOrEmpty(mailToAddress))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "收件人地址不能为空";
				return Json(resultInfo);
			}
			if (string.IsNullOrEmpty(subject))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "邮件标题不能为空";
				return Json(resultInfo);
			}
			if (string.IsNullOrEmpty(mailBody))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "邮件内容不能为空";
				return Json(resultInfo);
			}
			MailSender sender2 = new MailSender();
			sender2.Subject = subject;
			sender2.MailBody = mailBody;
			sender2.IsBodyHtml = true;
			sender2.FromName = (!string.IsNullOrEmpty(ConfigHelper.Get<SiteConfig>().SiteName)) ? ConfigHelper.Get<SiteConfig>().SiteName : "系统";
			//sender2.MailToAddressList.Add(new MailboxAddress(mailToAddress));
			sender2.MailToAddressList.Add(MailboxAddress.Parse(mailToAddress));
			//sender2.AttachmentFilePath = Utility.UploadDirPath(true) + "a.rar";
			if (sender2.Send() == MailState.Ok)
			{
				resultInfo.Status = 1;
				resultInfo.Msg = "邮件发送成功";
			}
			else
			{
				resultInfo.Status = 0;
				resultInfo.Msg = sender2.Msg;
			}
			return Json(resultInfo);
		}

		/// <summary>
		/// 得到国家、省份、城市、区域相对应的下拉选项代码
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult Region()
		{
			string Action = Utility.Request("Action", "country");
			string Country = Utility.Request("Country", "中华人民共和国");
			string Province = Utility.Request("Province");
			string City = Utility.Request("City");
			string Area = Utility.Request("Area");
			string Area1 = Utility.Request("Area1");
			string Area2 = Utility.Request("Area2");
			ResultInfo resultInfo = new ResultInfo();
			StringBuilder sb = new StringBuilder();
			sb.Append("<option value=\"\">请选择</option>");
			switch (Action.ToLower())
			{
				case "country":
					IList<RegionEntity> CountryList = _RegionServiceApp.GetCountryList();
					foreach (RegionEntity info in CountryList)
					{
						if (Country == info.Country)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.Country + "\">" + info.Country + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.Country + "\">" + info.Country + "</option>");
						}
					}
					break;
				case "province":
					IList<RegionEntity> ProvinceList = _RegionServiceApp.GetProvinceListByCountry(Country);
					foreach (RegionEntity info in ProvinceList)
					{
						if (Province == info.Province)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.Province + "\">" + info.Province + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.Province + "\">" + info.Province + "</option>");
						}
					}
					break;
				case "city":
					IList<RegionEntity> CityList = _RegionServiceApp.GetCityListByProvince(Province);
					foreach (RegionEntity info in CityList)
					{
						if (City == info.City)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.City + "\">" + info.City + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.City + "\">" + info.City + "</option>");
						}
					}
					break;
				case "area":
					IList<RegionEntity> AreaList = _RegionServiceApp.GetAreaListByCity(City);
					foreach (RegionEntity info in AreaList)
					{
						if (Area == info.Area)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.Area + "\">" + info.Area + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.Area + "\">" + info.Area + "</option>");
						}
					}
					break;
				case "area1":
					IList<RegionEntity> Area1List = _RegionServiceApp.GetArea1ListByArea(Area);
					foreach (RegionEntity info in Area1List)
					{
						if (Area1 == info.Area1)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.Area1 + "\">" + info.Area1 + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.Area1 + "\">" + info.Area1 + "</option>");
						}
					}
					break;
				case "area2":
					IList<RegionEntity> Area2List = _RegionServiceApp.GetArea2ListByArea1(Area1);
					foreach (RegionEntity info in Area2List)
					{
						if (Area2 == info.Area2)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.Area2 + "\">" + info.Area2 + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.Area2 + "\">" + info.Area2 + "</option>");
						}
					}
					break;
			}
			resultInfo.Status = 1;
			resultInfo.Data = sb.ToString();
			return Json(resultInfo);
		}

		/// <summary>
		/// 得到多级分类的下拉选项代码
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult IndustryCategory()
		{
			int ParentID = Utility.Request("ParentID", -1);
			int SelectCategory = Utility.Request("SelectCategory", -1);
			ResultInfo resultInfo = new ResultInfo();
			StringBuilder sb = new StringBuilder();
			sb.Append("<option value=\"\">请选择</option>");
			var list = _NodesServiceApp.GetNodesListByParentId(ParentID);
			foreach (var info in list)
			{
				if (SelectCategory == info.NodeID)
				{
					sb.Append("<option selected=\"selected\" value=\"" + info.NodeID + "\">" + info.NodeName + "</option>");
				}
				else
				{
					sb.Append("<option value=\"" + info.NodeID + "\">" + info.NodeName + "</option>");
				}
			}
			resultInfo.Status = 1;
			resultInfo.Data = sb.ToString();
			return Json(resultInfo);
		}

		/// <summary>
		/// 得到所属业务员相对应的下拉选项代码
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult MySales()
		{
			string Action = Utility.Request("Action", "SalesManager");
			int RoleID = Utility.Request("RoleID",0);
			string SalesManager = Utility.Request("SalesManager");
			string Sales = Utility.Request("Sales");
			ResultInfo resultInfo = new ResultInfo();
			StringBuilder sb = new StringBuilder();
			sb.Append("<option value=\"\">请选择</option>");
			switch (Action.ToLower())
			{
				case "salesmanager":
					IList<AdminEntity> AdminListSalesManager;
					if (RoleID > 0)
					{
						AdminListSalesManager = _AdminServiceApp.GetList(" AdminID IN (SELECT JXAR.AdminID FROM AdminRoles AS JXAR WHERE (JXAR.RoleID = @RoleID))", new { RoleID }).ToList();
					}
					else
					{
						AdminListSalesManager = _AdminServiceApp.GetList(p=>p.ParentAdminName=="").ToList();
					}
					foreach (var info in AdminListSalesManager)
					{
						if (SalesManager == info.AdminName)
						{
							sb.Append("<option selected=\"selected\" value=\"" + info.AdminName + "\">" + info.AdminName + "</option>");
						}
						else
						{
							sb.Append("<option value=\"" + info.AdminName + "\">" + info.AdminName + "</option>");
						}
					}
					break;
				case "sales":
					if (!string.IsNullOrEmpty(SalesManager))
					{
						IList<AdminEntity> AdminListSales = _AdminServiceApp.GetList(p => p.ParentAdminName == SalesManager).ToList();
						foreach (var info in AdminListSales)
						{
							if (Sales == info.AdminName)
							{
								sb.Append("<option selected=\"selected\" value=\"" + info.AdminName + "\">" + info.AdminName + "</option>");
							}
							else
							{
								sb.Append("<option value=\"" + info.AdminName + "\">" + info.AdminName + "</option>");
							}
						}
					}
					break;
			}
			resultInfo.Status = 1;
			resultInfo.Data = sb.ToString();
			return Json(resultInfo);
		}

		/// <summary>
		/// 得到枚举类型的说明
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public IActionResult GetEnumDescription()
		{
			string enumType = Utility.Request("enumType");
			int enumValue = Utility.Request("enumValue", -1);
			string result = string.Empty;
			switch (enumType)
			{
				case "GroupTypeEnum":
					result = EnumHelper.GetDescription((GroupTypeEnum)enumValue);
					break;
				case "UserStatusEnum":
					result = EnumHelper.GetDescription((UserStatusEnum)enumValue);
					break;
				case "NodeType":
					result = EnumHelper.GetDescription((JX.Core.Entity.NodeType)enumValue);
					break;
				case "LogCategory":
					result = EnumHelper.GetDescription((LogCategory)enumValue);
					break;
				case "LogPriority":
					result = EnumHelper.GetDescription((LogPriority)enumValue);
					break;
				case "FieldType":
					result = EnumHelper.GetDescription((JX.Infrastructure.Field.FieldType)enumValue);
					break;
				case "UserType":
					result = EnumHelper.GetDescription((UserTypeEnum)enumValue);
					break;
			}
			return Content(result);
		}

		/// <summary>
		/// 检查是否存在
		/// </summary>
		/// <param name="checkType"></param>
		/// <param name="checkValue"></param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult CheckIsExist(string checkType, string checkValue)
		{
			ResultInfo resultInfo = new ResultInfo();
			if(string.IsNullOrEmpty(checkValue))
				return Json(resultInfo);
			switch (checkType)
			{
				case "Title":
					if(_CommonInfoServiceApp.IsExist(p => p.Title == checkValue))
					{
						resultInfo.Status = 1;
						resultInfo.Msg = "该标题已存在";
					}
					break;
				case "UserName":
					if (_UsersServiceApp.IsExist(p => p.UserName == checkValue))
					{
						resultInfo.Status = 1;
						resultInfo.Msg = "该会员名已存在";
					}
					break;
			}
			return Json(resultInfo);
		}

		/// <summary>
		/// 生成二维码图片，返回图片地址。
		/// </summary>
		/// <param name="QRCodeText"></param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult CreateQRCode(string QRCodeText)
		{
			ResultInfo resultInfo = new ResultInfo();
			if (string.IsNullOrEmpty(QRCodeText))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "生成内容不能为空";
				return Json(resultInfo);
			}
			var data = QRCodeHelper.CreateQRCode(QRCodeText);
			if(!string.IsNullOrEmpty(data))
			{
				resultInfo.Status = 1;
				resultInfo.Msg = "生成成功";
				resultInfo.Data = data;
			}
			else
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "生成失败";
			}
			return Json(resultInfo);
		}

		private IActionResult RedirectToLocal(string returnUrl)
		{
			if (Url.IsLocalUrl(returnUrl))
			{
				return Redirect(returnUrl);
			}
			else
			{
				return RedirectToAction(nameof(HomeController.Index), "Home");
			}
		}
	}
}
